//
//  FANOAuthViewController.swift
//  Weibo - Swift
//
//  Created by user on 16/4/19.
//  Copyright © 2016年 user. All rights reserved.
//

import UIKit
import SVProgressHUD

let WB_APP_KEY = "1679233831"

let WB_REDIRECT_URI = "http://www.baidu.com/"

let WB_APP_SECRET = "4dd3577aaf85646ef9ae5793e6da1a0e"

class FANOAuthViewController: UIViewController,UIWebViewDelegate {
 
    lazy var webView:UIWebView = {
    
        let webView = UIWebView()
        
        webView.delegate = self
        
        return webView
        
    }()
    
    override func loadView() {
        
        view = webView
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_APP_KEY)&redirect_uri=\(WB_REDIRECT_URI)"
        
        let url = NSURL(string: urlString)
        
        let request = NSURLRequest(URL: url!)
        
        webView .loadRequest(request)
        
    }

    override func viewDidLoad() {
        super.viewDidLoad()


        setupUI()
    }
    
    func setupUI(){
        
        title = "登录"
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "autoInput")
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
    }
    
    func close(){
        
//        print("close")
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    func autoInput(){
        
//        print("autoInput")
        
         let jsString = "document.getElementById('userId').value='f474283547@163.com';document.getElementById('passwd').value='sgq474283547'"
        
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }

}

extension FANOAuthViewController {
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool{
        
        guard let req = request.URL else{
            
            return false
        }
        
        if req.absoluteString.hasPrefix(WB_REDIRECT_URI){

            if let query = req.query where query.containsString("code="){
                
                let code = query.substringFromIndex("code=".endIndex)
                
//                loadAccessToken(code)
                FANUserNetModel.sharedUserModel.loadAccessToken(code, finished: { (isSuccess) -> () in
                    
                    if isSuccess {
                        
                        print("登录成功")
                        self.dismissViewControllerAnimated(false, completion: { () -> Void in
                            
                            NSNotificationCenter.defaultCenter().postNotificationName(FANChangeRootVCNotification, object: nil)
                            
//                            UIApplication.sharedApplication().keyWindow?.rootViewController = FANWelcomeViewController()
                            
                            
                        })
                        
                    }else{
                        
                        print("登录失败")
                    }
                })
                
                
            }
            
            return false
        }
        
        return true
    }

    
    func webViewDidStartLoad(webView: UIWebView){
        
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView){
        
        SVProgressHUD.dismiss()
    }
    
}
